const fs = require('fs');

module.exports = function(path) {

    function iterator(url, dirs) {
        let stat = fs.statSync(url);
        if (stat.isDirectory()) {
            dirs.unshift(url);//收集目录
            inner(url, dirs);
        } else if (stat.isFile()) {
            fs.unlinkSync(url);//直接删除文件
        }
    }

    function inner(path, dirs) {
        let arr = fs.readdirSync(path);
        for (let i = 0, el; el = arr[i++];) {
            iterator(path + "/" + el, dirs);
        }
    }

    return new Promise((resolve, reject) => {
        let dirs = [];
        try {
            iterator(path, dirs);
            for (let i = 0, el; el = dirs[i++];) {
                fs.rmdirSync(el);//一次性删除所有收集到的目录
            }
            resolve();
        } catch (e) {//如果文件或目录本来就不存在，fs.statSync会报错，不过我们还是当成没有异常发生
            e.code === "ENOENT" ? reject() : reject(e);
        }
    });
};